<template>
  <view class="container">
    <view class="form">
      <view class="form-item">
        <input type="text" placeholder="用户名" @input="bindUsernameInput" />
      </view>
      <view class="form-item">
        <input type="password" placeholder="密码" @input="bindPasswordInput" />
      </view>
      <button @tap="login">登录</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
	  username:'',
      password: ''
    };
  },
  methods: {
    bindUsernameInput(e) {
      this.username = e.detail.value;
    },
    bindPasswordInput(e) {
      this.password = e.detail.value;
    },
    login() {
	  console.log('UserName:', this.username);
      console.log('Password:', this.password); // 打印密码
      if (!this.username || !this.password) {
        uni.showToast({
          title: '用户名或密码不能为空',
          icon: 'none'
        });
        return;
      }
      // 构建带有用户名和密码的查询参数
      const params = `user=${encodeURIComponent(this.username)}&pwd=${encodeURIComponent(this.password)}`;
      uni.request({
        url: `http://127.0.0.1:8081/login_user/?${params}`, // 修改为正确的API接口
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.id) {
            // 登录成功，获取用户ID
            const userId = res.data.id;
			console.log(userId);
            // 处理用户信息
            console.log('用户信息:', res.data);
            uni.showToast({
              title: '登录成功',
              icon: 'success'
            });
            // 处理用户信息
            const userInfo = res.data;
            // 将用户信息保存到全局变量中
            getApp().globalData.userInfo = userInfo;
            // 跳转到个人页面
            uni.navigateTo({
              url: '/pages/personal/personal'
            });
          } else {
            uni.showToast({
              title: '登录失败',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('请求失败:', error);
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    }
  }
}
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.form {
  width: 90%;
}

.form-item {
  margin-bottom: 20rpx;
}

input {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 10rpx;
  width: 100%;
}

button {
  background-color: #1AAD19;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10rpx;
  width: 100%;
}
</style>